package cn.iune.backcenter.authen;

import java.sql.SQLException;
import java.text.ParseException;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.justep.baas.data.Row;
import com.justep.baas.data.RowState;
import com.justep.baas.data.Table;
import com.justep.baas.data.Transform;


@Transactional
@Service
public class SaOppersonServiceImpl implements ISaOppersonService {

	
	@Autowired
	private ISaOppersonDao dao;
	
	public SaOppersonServiceImpl(){
//		dao = new SaOppersonDaoJPAImpl();
	}
	
	/* (non-Javadoc)
	 * @see com.iune.platform.security.ISaOppersonService#insert(com.iune.platform.security.SaOpperson)
	 */
	@Transactional
	@Override
	public void insert(SaOpperson obj){
		dao.insert(obj);
	}

	/* (non-Javadoc)
	 * @see com.iune.platform.security.ISaOppersonService#delete(java.lang.String)
	 */
	@Transactional
	@Override
	public void delete(String fID){
		dao.delete(fID);
	}

	/* (non-Javadoc)
	 * @see com.iune.platform.security.ISaOppersonService#update(com.iune.platform.security.SaOpperson)
	 */
	@Transactional
	@Override
	public void update(SaOpperson obj) {
		dao.update(obj);
	}

	/* (non-Javadoc)
	 * @see com.iune.platform.security.ISaOppersonService#getByID(java.lang.String)
	 */
	@Override
	public SaOpperson getByID(String fID) {
		return dao.getByID(fID);
	}
	
	@Override
	public List<SaOpperson> getAll() {
		return dao.getAll();
	}

	/* (non-Javadoc)
	 * @see com.iune.platform.security.ISaOppersonService#getByLoginName(java.lang.String)
	 */
	@Override
	public SaOpperson getByLoginName(String sLoginName) {
		return dao.getByLoginName(sLoginName);
	}
	
	
	/*
	public JSONObject query(JSONObject data) throws Throwable {
		
		// 获取参数
		Object columns = data.getJSONObject("columns"); // 列定义
		Integer limit = data.getInteger("limit"); // 分页查询的行数
		Integer offset = data.getInteger("offset"); // 分页查询的行偏移
		String search = data.getString("search"); // 检索关键字
		String filter = data.getString("filter"); // 过滤条件
		String id = data.getString("id");

		
		// 存放SQL中的参数值
		List<Object> sqlParams = new ArrayList<Object>();
		// 存放SQL中的过滤条件
		List<String> filters = new ArrayList<String>();
		if (Utils.isNotEmptyString(search)) {
			// 增加过滤条件
			filters.add("sCode LIKE ? OR sName LIKE ? OR sLoginName LIKE ? OR sMail LIKE ? OR sMobilePhone LIKE ?");
			// 检索关键字中如果没有%，则前后自动加%
			search = (search.indexOf("%") != -1) ? search : "%" + search + "%";
			// sqlParams的参数个数和顺序必须与过滤条件的?相匹配 
			for (int i = 0; i < 5; i++) {
				sqlParams.add(search);
			}
		}
		//处理过滤条件
		if (Utils.isNotEmptyString(filter)) {
			filters.add(filter);
		}
		//处理id
		if (Utils.isNotEmptyString(id)) {
			filters.add("sID='"+id+"'");
		}
	
		
		Table table = Transform.createTableByColumnsDefine((JSONObject) columns);
		
		if (offset != null && offset.equals(0)) {
			long rowCount = dao.getCount(filters, sqlParams);
			table.setTotal((int)rowCount);
		}

		String orderBy = "sName DESC";
				
		//获取数据
		List<Row> rows = listToRows(dao.query(filters,orderBy,sqlParams,offset,limit));
	    table.appendRows(rows);
		JSONObject json = Transform.tableToJson(table);
	
		return json;
	}


	public int save(JSONObject object) throws Throwable  {
		// TODO Auto-generated method stub
		// JSON转换Table
		Table table = Transform.jsonToTable(object);
		List<SaOpperson> list = rowsToList(table.getRows());
		for(SaOpperson obj : list){
			if(RowState.NEW.equals(obj.getRowState())){
				dao.insert(obj);
			}
			if(RowState.EDIT.equals(obj.getRowState())){
				dao.update(obj);
			}
			if(RowState.DELETE.equals(obj.getRowState())){
				dao.delete(obj.getsID());
			}
		}
		return 0;
	}

	public List<Row> listToRows(List<SaOpperson> list){
		//添加行集
		List<Row> rows = new ArrayList<Row>();
		//循环行
	    for(SaOpperson o : list){
	    	rows.add(objectToRow(o));
	    }
	    return rows;
	}

	public List<SaOpperson> rowsToList(List<Row> rows){
		//添加行集
		List<SaOpperson> list = new ArrayList<SaOpperson>();
		//循环行
	    for(Row r : rows){
	    	list.add(rowToObject(r));
	    }
	    return list;
	}

	public Row objectToRow(SaOpperson obj){
    	
		Map<String, ColumnValue> values = new HashMap<String, ColumnValue>();
		//循环行中每一列
		ColumnValue value = new ColumnValue(obj.getsID());
		values.put("sID", value);
		
		value = new ColumnValue(obj.getsName());
 		values.put("sName", value);
		value = new ColumnValue(obj.getsCode());
 		values.put("sCode", value);
		value = new ColumnValue(obj.getsIDCard());
 		values.put("sIDCard", value);
		value = new ColumnValue(obj.getsNumb());
 		values.put("sNumb", value);
		value = new ColumnValue(obj.getsLoginName());
 		values.put("sLoginName", value);

 
		value = new ColumnValue(obj.getsPassword());
 		values.put("sPassword", value);
		value = new ColumnValue(obj.getsPasswordTimeLimit());
 		values.put("sPasswordTimeLimit", value);
		value = new ColumnValue(obj.getsPasswordModifyTime());
 		values.put("sPasswordModifyTime", value);
		value = new ColumnValue(obj.getsMainOrgID());
 		values.put("sMainOrgID", value);
		value = new ColumnValue(obj.getsSafeLevelID());
 		values.put("sSafeLevelID", value);
		value = new ColumnValue(obj.getsSequence());
 		values.put("sSequence", value);
		value = new ColumnValue(obj.getsValidState());
 		values.put("sValidState", value);
		value = new ColumnValue(obj.getsDescription());
 		values.put("sDescription", value);


//		value = new ColumnValue(obj.getsPhoto());
// 		values.put("sPhoto", value);
		value = new ColumnValue(obj.getsSex());
 		values.put("sSex", value);
		value = new ColumnValue(obj.getsBirthday());
 		values.put("sBirthday", value);
		value = new ColumnValue(obj.getsJoinDate());
 		values.put("sJoinDate", value);
		value = new ColumnValue(obj.getsHomePlace());
 		values.put("sHomePlace", value);
		value = new ColumnValue(obj.getsCountry());
 		values.put("sCountry", value);
		value = new ColumnValue(obj.getsProvince());
 		values.put("sProvince", value);
		value = new ColumnValue(obj.getsCity());
 		values.put("sCity", value);
 		
		value = new ColumnValue(obj.getsDegree());
 		values.put("sDegree", value);
		value = new ColumnValue(obj.getsGraduateSchool());
 		values.put("sGraduateSchool", value);
		value = new ColumnValue(obj.getsSpeciality());
 		values.put("sSpeciality", value);
		value = new ColumnValue(obj.getsSchoolLength());
 		values.put("sSchoolLength", value);
		value = new ColumnValue(obj.getsTitle());
 		values.put("sTitle", value);
		value = new ColumnValue(obj.getsMarriage());
 		values.put("sMarriage", value);
		value = new ColumnValue(obj.getsCardNO());
 		values.put("sCardNO", value);
		value = new ColumnValue(obj.getsCardKind());
 		values.put("sCardKind", value);
 		
		value = new ColumnValue(obj.getsFamilyAddress());
 		values.put("sFamilyAddress", value);
		value = new ColumnValue(obj.getsZip());
 		values.put("sZip", value);
		value = new ColumnValue(obj.getsMsn());
 		values.put("sMsn", value);
		value = new ColumnValue(obj.getsQQ());
 		values.put("sQQ", value);
		value = new ColumnValue(obj.getsMail());
 		values.put("sMail", value);
		value = new ColumnValue(obj.getsMobilePhone());
 		values.put("sMobilePhone", value);
		value = new ColumnValue(obj.getsFamilyPhone());
 		values.put("sFamilyPhone", value);
		value = new ColumnValue(obj.getsOfficePhone());
 		values.put("sOfficePhone", value);
		value = new ColumnValue(obj.getsEnglishName());
 		values.put("sEnglishName", value);

		value = new ColumnValue(obj.getRegisterDate());
 		values.put("registerDate", value);
		value = new ColumnValue(obj.getValidataCode());
 		values.put("validataCode", value);
		value = new ColumnValue(obj.getsMailState());
 		values.put("sMailState", value);
		value = new ColumnValue(obj.getsMobileState());
 		values.put("sMobileState", value);

		value = new ColumnValue(obj.getsCreatorFID());
 		values.put("sCreatorFID", value);

		value = new ColumnValue(obj.getVersion());
 		values.put("version", value);
		
		Row row = new Row(values,RowState.NONE);
		return row;
	}
	
	public SaOpperson rowToObject(Row row){
		SaOpperson obj = new SaOpperson();
		obj.setsID(row.getString("sID"));
		
		obj.setsName(row.getString("sName"));
		obj.setsCode(row.getString("sCode"));
		obj.setsIDCard(row.getString("sIDCard"));
		obj.setsNumb(row.getInteger("sNumb"));
		obj.setsLoginName(row.getString("sLoginName"));
		obj.setsPassword(row.getString("sPassword"));
		obj.setsPasswordTimeLimit(row.getInteger("sPasswordTimeLimit"));
		obj.setsPasswordModifyTime(row.getDate("sPasswordModifyTime"));
		
		obj.setsMainOrgID(row.getString("sMainOrgID"));
		obj.setsSafeLevelID(row.getString("sSafeLevelID"));
		obj.setsSequence(row.getInteger("sSequence"));
		obj.setsValidState(row.getInteger("sValidState"));
		obj.setsDescription(row.getString("sDescription"));
//		obj.setsPhoto(row.getColumnValue("sPhoto")));
		obj.setsSex(row.getString("sSex"));

		obj.setsBirthday(row.getDate("sBirthday"));
		obj.setsJoinDate(row.getDate("sJoinDate"));
		obj.setsHomePlace(row.getString("sHomePlace"));
		obj.setsCountry(row.getString("sCountry"));
		obj.setsProvince(row.getString("sProvince"));
		obj.setsCity(row.getString("sCity"));

		obj.setsDegree(row.getString("sDegree"));
		obj.setsGraduateSchool(row.getString("sGraduateSchool"));
		obj.setsSpeciality(row.getString("sSpeciality"));
		obj.setsSchoolLength(row.getString("sSchoolLength"));
		obj.setsTitle(row.getString("sTitle"));
		obj.setsMarriage(row.getString("sMarriage"));
		obj.setsCardNO(row.getString("sCardNO"));
		obj.setsCardKind(row.getString("sCardKind"));
		
		obj.setsFamilyAddress(row.getString("sFamilyAddress"));
		obj.setsZip(row.getString("sZip"));
		obj.setsMsn(row.getString("sMsn"));
		obj.setsQQ(row.getString("sQQ"));
		obj.setsMail(row.getString("sMail"));
		obj.setsMobilePhone(row.getString("sMobilePhone"));
		obj.setsFamilyPhone(row.getString("sFamilyPhone"));
		obj.setsOfficePhone(row.getString("sOfficePhone"));
		obj.setsEnglishName(row.getString("sEnglishName"));
		
		obj.setRegisterDate(row.getDateTime("registerDate"));
		obj.setValidataCode(row.getString("validataCode"));
		obj.setsMailState(row.getInteger("sMailState"));
		obj.setsMobileState(row.getInteger("sMobileState"));
		
		obj.setsCreatorFID(row.getString("sCreatorFID"));
		
		obj.setVersion(row.getInteger("version"));
		
		obj.setRowState(row.getState());

		return obj;
	}
	 */	
	
	/*
	 * 唯一性检查
	 * 参数与save函数的参数相同
	 * 返回值：通过检查（唯一），true；否则返回false
	 * 单独由controller调用，而不是放在下面的save函数中调用，避免每一次save都进行唯一性检查
	 */
	@Override
	public boolean checkUnique(JSONObject object) throws Throwable {
		Table table = Transform.jsonToTable(object);
		List<Row> list = table.getRows();
		for(Row row : list){
			JSONObject javaObject= Transform.rowToJavaObject(table, row);
			SaOpperson obj = JSON.toJavaObject(javaObject, SaOpperson.class);
			if(RowState.NEW.equals(obj.getRowState())){
				SaOpperson oobj = dao.getByLoginName(obj.getsLoginName());
				if(oobj!=null) {
					//已经存在
					return false;
				}
//				SaOpperson oobj1 = dao.getByMail(obj.getsMail());
//				if(oobj1!=null) {
//					//已经存在
//					return false;
//				}
//				SaOpperson oobj2 = dao.getByMobilePhone(obj.getsMobilePhone());
//				if(oobj2!=null) {
//					//已经存在
//					return false;
//				}
			}
			if(RowState.EDIT.equals(obj.getRowState())){
				SaOpperson oobj = dao.getByLoginName(obj.getsLoginName());
				if(oobj!=null && !oobj.getsID().equals(obj.getsID())) {
					return false;
				}
//				SaOpperson oobj1 = dao.getByMail(obj.getsMail());
//				if(oobj1!=null && !oobj1.getsID().equals(obj.getsID())) {
//					return false;
//				}
//				SaOpperson oobj2 = dao.getByMobilePhone(obj.getsMobilePhone());
//				if(oobj2!=null && !oobj2.getsID().equals(obj.getsID())) {
//					return false;
//				}
			}
		}
		return true;
	}

	@Transactional
	@Override
	public JSONObject save(JSONObject object) throws ParseException {
		// TODO Auto-generated method stub
		// JSON转换Table
		Table table = Transform.jsonToTable(object);
		JSONObject json = new JSONObject();
		json.put("concept", "SaOpperson");
		List<Row> list = table.getRows();
		for(Row row : list){
			JSONObject javaObject= Transform.rowToJavaObject(table, row);
			SaOpperson obj = JSON.toJavaObject(javaObject, SaOpperson.class);
			if(RowState.NEW.equals(obj.getRowState())){
				dao.insert(obj);
			}
			if(RowState.DELETE.equals(obj.getRowState())){
				dao.delete(obj.getsID());
			}
			if(RowState.EDIT.equals(obj.getRowState())){
				dao.update(obj);
			}
		}
		
		json.put("code", 0);
		json.put("msg", "success");
		
		return json;
	}


	//设置主岗
	/* (non-Javadoc)
	 * @see com.iune.platform.security.ISaOppersonService#updateMainOrgByID(java.lang.String, java.lang.String)
	 */
	@Transactional
	@Override
	public void updateMainOrgByID(String sID,String orgID){
		SaOpperson obj = dao.getByID(sID);
		obj.setsMainOrgID(orgID);
		dao.update(obj);
	}

	
	@Transactional
	@Override
	public JSONObject getUserinfo(String sLoginName) { 
		SaOpperson saOpperson= dao.getByLoginName(sLoginName);
		if(saOpperson==null) {
			//返回用户 
			JSONObject json = new JSONObject();
			json.put("code", -1);
			json.put("msg", "failure");
			json.put("status", "失败！");
			return json;
		}else {
			//返回用户 
			JSONObject json = new JSONObject();
			json.put("code", 0);
			json.put("msg", "success");
			json.put("status", "成功！");
			
			JSONObject data = new JSONObject();
			data.put("sLoginName", saOpperson.getsLoginName());
			data.put("userId", saOpperson.getsID());
			data.put("cUsercode", saOpperson.getsCode());
			data.put("cUsername", saOpperson.getsName());
			String images = saOpperson.getImages();
			if(images==null) {
				images = new JSONArray().toJSONString();
			}
			data.put("images", images);
			
			json.put("data", data);
			return json;
		}
		
	}
	
	@Transactional
	@Override
	public int updateName(String sLoginName, String sName) { 
		SaOpperson saOpperson= dao.getByLoginName(sLoginName);
		if(saOpperson==null) {
			return -1;
		}else {
			saOpperson.setsName(sName);
			dao.update(saOpperson);
			return 0;
		}
	}

	@Transactional
	@Override
	public int updateEmail(String id,String email) { 
		SaOpperson saOpperson= dao.getByID(id);
		saOpperson.setsMail(email);
		dao.update(saOpperson);
		return 0;
	}


	@Override
	public JSONObject newData(JSONObject param) {
		return dao.create(param);
	}
	
	@Override
	public JSONObject deleteData(JSONObject param) {
		//System.out.println("fileFactoryCreate.param-->>"+param.toJSONString());
		JSONArray ids = param.getJSONArray("ids");
		for(int i=0;i<ids.size();i++){
			String id = ids.getString(i);
			//这里可以增加是否可删除的判断
			
			dao.delete(id);
		}

		JSONObject data = new JSONObject();
		data.put("ids", ids);
		
		JSONObject json = new JSONObject();
		json.put("code", 0);
		json.put("msg", "success");
		json.put("data", data);
		
		return json;
	}

	/*
	在@Transaction注解中定义noRollbackFor和RollbackFor指定某种异常是否回滚。 
	@Transactional(noRollbackFor=RuntimeException.class) 
	@Transactional(RollbackFor=Exception.class) 
	*/
	@Transactional
	@Override
	public JSONObject saveData(JSONObject param) {
		//Spring的事务管理默认只对出现运行期异常(java.lang.RuntimeException及其子类)进行回滚。 
		//如果一个方法抛出Exception或者Checked异常，Spring事务管理默认不进行回滚。 
		// JSON转换Table
		//System.out.println(object);
		JSONObject data;
		try {
			data = this.save(param);
					
			JSONObject json = new JSONObject();
			json.put("code", 0);
			json.put("msg", "success");
			json.put("data", data);
			
			return json;
			
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			
			JSONObject json = new JSONObject();
			json.put("code", -1);
			json.put("msg", e.getMessage());
			
			return json;
		} 
	}
	
	/* (non-Javadoc)
	 * @see com.iune.erp.baseinfo.aaa#queryJDBC(com.alibaba.fastjson.JSONObject)
	 */
	@Transactional(propagation=Propagation.NOT_SUPPORTED,readOnly=true)
	@Override
	public JSONObject queryData(JSONObject param){
		//在此层面（ServiceImpl）统一处理异常，此层面直接被controller调用，面对BizData
		
		try {
			JSONObject jsonTable = dao.query(param);
			
			JSONObject json = new JSONObject();
			json.put("code", 0);
			json.put("msg", "success");
			json.put("data", jsonTable);
			
			return json;
		} catch (SQLException e) {
			e.printStackTrace();
			
			JSONObject json = new JSONObject();
			json.put("code", -1);
			json.put("msg", e.getMessage());
			return json;
		}
	}

	@Override
	public JSONObject validData(JSONObject param) {
		// TODO Auto-generated method stub
		return null;
	}
}
